package com.qinker.robot.hook.util;

import com.alibaba.fastjson.JSON;
import com.qinker.robot.common.model.Employee;
import com.qinker.robot.common.model.PrivateChatRequest;
import com.qinker.robot.hook.data.M;
import com.qinker.robot.hook.data.ding.EmployeeObject;
import com.qinker.robot.hook.plugin.dingding.DingDingPlugin;
import com.qinker.robot.hook.plugin.interfaces.XConfig;
import com.qinker.robot.hook.plugin.interfaces.XConfigManager;
import com.qinker.robot.hook.plugin.interfaces.XPluginManager;
import com.sky.xposed.common.util.Alog;

import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;

import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_LoadPackage;

/**
 * 钉钉HOOK工具类
 * Created by Irany 2019/10/26 0026 23:03
 */
public class DingHookUtils {

    private XC_LoadPackage.LoadPackageParam mParam;

    private XPluginManager pluginManager;

    private XConfigManager configManager;

    private XConfig xConfig;
    private static DingHookUtils instance;

    public DingHookUtils(XPluginManager pluginManager) {
        this.pluginManager = pluginManager;
        mParam = pluginManager.getLoadPackageParam();
        xConfig = this.pluginManager.getVersionManager().getSupportConfig();
        configManager = this.pluginManager.getConfigManager();
    }

    public static DingHookUtils getInstance() {
        return instance;
    }


    public static void init(XPluginManager pluginManager) {
        if (instance == null) {
            synchronized (DingHookUtils.class) {
                if (instance == null) {
                    instance = new DingHookUtils(pluginManager);
                }
            }
        }
        Alog.i("DING HOOK工具类初始化成功 " + JSON.toJSONString(instance));
    }

    /**
     * 搜索一个企业员工
     */
    public Employee searchOrgStaff(String keyword) throws Exception {
        //如果本地缓存有数据则取出来
        Alog.d("从缓存搜索企业员工: " + keyword);
        if (DingDingPlugin.userCache.containsKey(keyword)) {
            return DingDingPlugin.userCache.get(keyword);
        }

        Alog.d("从钉钉搜索企业员工-start: " + keyword);
        Class<?> globalSearchFragmentClass = XposedHelpers.findClass(xConfig.get(M.classz.CLASS_ANDROID_SEARCH_FRAGMENT_GLOBALSEARCHFRAGMENT), mParam.classLoader);
        Object globalSearchFragment = globalSearchFragmentClass.newInstance();
        Method searchMethod = globalSearchFragmentClass.getDeclaredMethod("a", String.class);
        searchMethod.invoke(globalSearchFragment, keyword);
        Alog.d("从钉钉搜索企业员工-end: " + keyword);
        return DingDingPlugin.userCache.get(keyword);
    }

    public boolean sendMessage(String cid, String message) {
        try {
            String uid = cid.split(":")[0];
            //Object conversation = DingCloneObject.conversation;
            Class<?> conversationClass = XposedHelpers.findClass("com.alibaba.wukong.im.conversation.ConversationImpl", mParam.classLoader);
            Object conversation = conversationClass.newInstance();
            Field mCidField = conversation.getClass().getDeclaredField("mCid");
            //String mCid = (String) mCidField.get(conversation);
            mCidField.setAccessible(true);
            mCidField.set(conversation, cid);
            //mCidField.set(conversation, uid + ":" + mCid.split(":")[1]);
            Field mIconField = conversation.getClass().getDeclaredField("mIcon");
            mIconField.setAccessible(true);
            mIconField.set(conversation, uid);


            Field mTitleField = conversation.getClass().getDeclaredField("mTitle");
            mTitleField.setAccessible(true);
            mTitleField.set(conversation, uid);

            String classStr = xConfig.get(M.classz.CLASS_DEFPACKAGE_CHAT_MESSAGE_SENDER);
            Class<?> messageImpl = XposedHelpers.findClass(classStr, mParam.classLoader);
            Object messageImplObj = messageImpl.getConstructor(conversation.getClass().getInterfaces()[0]).newInstance(conversation);


            XposedHelpers.callMethod(messageImplObj, "a", message, new HashMap<>(), new HashMap<>());
            return true;
        } catch (Exception e) {
            Alog.e(e.getMessage(), e);
        }
        return false;
    }

    /**
     * 发送消息
     */
    public boolean sendMessage(PrivateChatRequest request) {
        return sendMessage(request.getDingUid() + ":736754249", request.getMessage());
    }

    private Employee toEmployee(EmployeeObject object) {
        Employee employee = new Employee();
        employee.setOrgId(object.getOrgId());
        employee.setOrgName(object.getOrgName());
        employee.setOrgNickName(object.getOrgNickName());
        employee.setOrgStaffId(object.getOrgStaffId());
        return employee;
    }

    /**
     * 根据参数个数查找对应的方法
     */
    private Method findMethod(String className, String methodName, int paramCount) {
        Class<?> clazz = XposedHelpers.findClass(className, mParam.classLoader);
        for (Method method : clazz.getDeclaredMethods()) {
            if (StringUtils.equals(methodName, method.getName()) && method.getParameterTypes().length == paramCount) {
                return method;
            }
        }
        return null;
    }

}
